<?php
//测试控制器类
class IndexControl extends Control{
    function index(){
    	// print_const();
    	$category = catched('category');
    	$categoryData = Data::channelLevel($category);
    	$this->assign('categoryData',$categoryData);

        $this->display('index.html');
    }

    function content(){

        $gid = Q('gid');
        $pre = C('DB_PREFIX');
        $goods = M('goods')->where(array('gid'=>$gid))->find();

        $goods['goods_pic'] = M('goods_pic')->where(array('goods_gid'=>$gid))->all();
        $gtid = $goods['gtid'];
        $attr = M('attr_class')->where(array('gt_id'=>$gtid,'is_spec'=>1))->all();
        // 获得该商品规格属性
        if(!empty($attr)){
             foreach ($attr as $key => $class) {
               $sql = 'SELECT ga.avid,ga.attr_value FROM '.$pre.'attr_value'.' AS av JOIN '.
                        $pre.'goods_attr AS ga ON av.av_id=ga.avid WHERE gid='.$gid.' AND av.ac_id='.$class['ac_id'];
                $attr[$key]['specValue'] = M()->query($sql);
            }
        }
       
        $avid = Q('avid');
        if($avid){//存在avid说明不是第一次加载
            $avid = Q('avid');
            $avid = explode('-', $avid);
            $goodsStock = $this->checkStock($gid,$avid);
            $goodsStock = current($goodsStock);
            $stockAvid = $avid;
        }else{//第一次加载

            $goodsStock = M('stock')->where(array('gid'=>$gid))->find();
           
            $stockAvid = M('stock_attr')->where(array('stid'=>$goodsStock['stid']))->getField('av_id',true);
            
        }
         //根据库存中PIC_ID取出goods_pic中存放的该款商品对应的款式图片           
        $goodsStock['spec_pic'] = M('goods_pic')->where(array('pic_id'=>$goodsStock['pic_id']))->find();

        $goods = array_merge($goods,$goodsStock);
        // 获得我的位置的相关数据
        $ca = catched('category');
        $cid = $goods['cid'];
        $ca = Data::parentChannel($ca,$cid);
        $newCa = array();
        $l = count($ca);
        //我的位置倒序
        for($i=0;$i<$l;$i++){
            $newCa[$i] = $ca[$l-$i-1];
        }
        $ca = $newCa;
         // 获得我的位置的相关数据结束
         
        $this->assign('ca',$ca);//分配我的位置，所有父级栏目数据
        $this->assign('stockAvid',$stockAvid);//分配规格选中的当前样式参数
        $this->assign('attr',$attr);//分配商品规格，作为由规格筛选库存的条件
        $this->assign('goods',$goods);//分配商品信息（价格，库存）
        $this->assign('spec_value',Q('spec'));
      

    	$this->display('goods.html');
    }
//点击规格时，异步获得该规格是否有库存
    public function hasStock(){
        $gid = Q('gid',0,'intval');
        $avid = Q("avid");
        $avid = explode('-',$avid);
        if($this->checkStock($gid,$avid)){
            echo 1;exit;
        }else{
            echo 0;exit;
        }
       
    }
    /**
     * 通过avid gid检测商品是否有库存
     * @param  [type] $gid  [description]
     * @param  [type] $avid [description]
     * @return [type]       [description]
     */
    function checkStock($gid,$avid){
        $table = ' '.C('DB_PREFIX').'stock_attr ';
        $pre = ' '.C('DB_PREFIX');
        $join = '';
        $as = 's';
        $on = '';
        $where = '';
        foreach ($avid as $key => $value) {
            $join.= $table.' AS '.$as.$key.' JOIN ';
            $where.= $as.$key.'.av_id='.$value.' AND ';
        }
        $where =' WHERE '.$where;
        $join = substr($join,0,-5);
        //组合ON
        
        for ($i=0;$i<count($avid)-1;$i++) {
           $on.= ' ON '.$as.$i.'.stid='.$as.($i+1).'.stid'; 

        }
        $sql = 'SELECT s0.stid FROM '.$join.$on.$where.' s0.gid='.$gid;

        $stid = M()->query($sql);
        if(empty($stid)){
            return 0;
        }else{
            $sql = 'SELECT * FROM '.$pre.'stock WHERE stid='.$stid[0]['stid']; 
            $stock = M()->query($sql);
            $stockNum = $stock[0]['stock'];
            if($stockNum>0){
                return $stock;
            }else{
                return 0;
            }
        }
    }

    function category(){
        $cid = Q('cid',0,'intval');
        $categoryData = catched('category');    
        $gtid = $categoryData[$cid]['gtid'];

        // 获得我的位置的相关数据
        $ca = catched('category');
       
        $ca = Data::parentChannel($ca,$cid);
        $newCa = array();
        $l = count($ca);
        //我的位置倒序
        for($i=0;$i<$l;$i++){
            $newCa[$i] = $ca[$l-$i-1];
        }
        $ca = $newCa;
         // 获得我的位置的相关数据结束
        $this->assign('ca',$ca);//分配我的位置，所有父级栏目数据

        //查找当前cid下是否有子级以下栏目
        $childCategory = array();
        foreach ($categoryData as $key => $value) {
            if(DATA::isChild($categoryData, $key,  $cid)){
                $childCategory[] = $value; 
            }
        }

        $num = M('attr_class')->where(array('gt_id'=>$gtid))->count();

        if(!empty($childCategory) or !$num){//如果有子栏目，那么进入栏目分级类表。显示子栏目名，和所有以下栏目商品（包括自身）
            $count=0;
            $goodsData = array();
            //将自身栏目商品加入
            $count+= M('goods')->where(array('cid'=>$cid))->count();
            $goods = M('goods')->where(array('cid'=>$cid))->Field()->all();
            if(!empty($goods)){
                $goodsData = array_merge($goodsData,$goods);
            }
            // 将子栏目商品加入
            foreach ($childCategory as $key => $cc) {
                $count += M('goods')->where(array('cid'=>$cc['cid']))->count();
                // $page = new Page($count,20);
                $goods = M('goods')->where(array('cid'=>$cc['cid']))->Field()->all();
                if(empty($goods)){
                   continue;
                }
                $goodsData = array_merge($goodsData,$goods);
            }
            // $this->assign('page',$page->show());
            $this->assign('goodsData',$goodsData);

            $this->assign('childCategory',$childCategory);//分配子级栏目

            $this->display('childGoods_list.html');

        }else{
            if(M('goods')->where(array('cid'=>$cid))->all()){
                // 该栏目下有数据的时候
                

                 if(!Q('get.s')){
                    $num = M('attr_class')->where(array('gt_id'=>$gtid))->count();
                    $attr='';
                    for ($i=0; $i <$num ; $i++) { 
                        $attr.='0-';
                    }
                    $attr = substr($attr,0,-1);
                    go(U('category',array('cid'=>$cid,'s'=>$attr)));
                }
                // 分配商品列表
                $this->assignGoods();
                // 份配属性值
                $this->assignAttrValue($gtid);
            }else{
                //该栏目下无数据，直接显示模板
            }
               
            $this->display('goods_list.html');
        }
        
        
    }

    protected function display($tplFile=null, $cacheTime = null, $cachePath = null, $stat = false, $contentType = "text/html", $charset = "", $show = true){
    	$tplFile=C('TPL_PATH').C('TPL_STYLE').'/'.$tplFile;
		parent::display($tplFile);
    }

    function assignAttrValue($gtid){
        $attrData = M('attr_class')->where(array('gt_id'=>$gtid))->all();
        foreach ($attrData as $key => $attr) {
           $attrData[$key]['attrValue'] = M('attr_value')->where(array('ac_id'=>$attr['ac_id']))->all();
        }
        $this->assign('attrData',$attrData);
    }
    function assignGoods(){
        $s = Q('s');
        $s = explode('-', $s);
        $searcheAttr=array();
        foreach ($s as $key => $value) {
           if($value==0)continue;
           $searcheAttr[] = $value;
        }
        // 如果属性id全是零,那么显示该栏目下全部商品
        if(empty($searcheAttr)){
            $count = M('goods')->where(array('cid'=>Q('cid')))->count();
            $page = new Page($count,20);
            $goodsData = M('goods')->where(array('cid'=>Q('cid')))->limit($page->limit())->all();
           
            $this->assign('page',$page->show());
            $this->assign('goodsData',$goodsData);
        }else{
            $sql = '';
            $where = ' WHERE ';
            $on = ' ON ';
            $join = ' ';
            $table = C('DB_PREFIX').'goods_attr'.' AS ';
            $and = ' AND ';
            $a = 'a';
            //组合JOIN字段
            foreach ($searcheAttr as $key => $attr) {
                $join.= $table.$a.$key.' JOIN ';
                //组合where字段
                $where.=$a.$key.'.avid= '.$attr.' AND ';
            }
            //组合ON字段
            for($i=0;$i<count($searcheAttr)-1;$i++){
                
                $on.= $a.$i.'.gid='.$a.($i+1).'.gid AND ';
            }
            $where.= 'g.cid='.Q('cid',0,'intval');
            $join =  substr($join, 0,-5);
            $on.='a0.gid = g.gid';
           
            $countSQL = 'SELECT count("*") AS c FROM hd_g_goods AS g JOIN '.$join.$on.$where;
            $count = M()->query($countSQL);
            $page = new Page($count[0]['c'],20);
            $sql .= 'SELECT * FROM hd_g_goods AS g JOIN '.$join.$on.$where." LIMIT ".$page->limit(true);
            $goodsData = M()->query($sql);
            $this->assign('page',$page->show());
            $this->assign('goodsData',$goodsData);
        }
    }

    public function search(){
        $keyword = $_POST['keyword'];
        if($keyword){
            $pre = C('DB_PREFIX');
            $sql = 'SELECT * FROM '.$pre.'goods WHERE gname LIKE "%'.$keyword.'%"';
            $data = M()->query($sql);
            $this->assign('goodsData',$data);
            $this->display('goods_list');
        }else{
            go(__HISTORY__);
        }
       
    }
}
?>